package com.lujieni.moon.utils;

import com.auth0.jwt.JWT;
import com.auth0.jwt.JWTVerifier;
import com.auth0.jwt.algorithms.Algorithm;
import com.auth0.jwt.interfaces.DecodedJWT;
import org.bouncycastle.util.encoders.Base64;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.nio.charset.Charset;
import java.security.KeyFactory;
import java.security.interfaces.RSAPrivateKey;
import java.security.interfaces.RSAPublicKey;
import java.security.spec.PKCS8EncodedKeySpec;
import java.security.spec.X509EncodedKeySpec;
import java.util.Date;

/**
 * @author 陈宇霖
 * @version V1.0
 * @Title JWTUtils
 * @Package com.itiaoling.dedication.util
 * @Description jwt校验器
 * @date 1/28/19 11:28
 */
public class JWTUtils {

    private Logger logger = LoggerFactory.getLogger(getClass());

    /**
     * RSA公钥
     */
    private String publicKey;

    /**
     * RSA私钥
     */
    private String privateKey;

    private static final String JWT_ISSUER = "OC-Server";
    private static final String JWT_AUDIENCE = "OC-Client";
    private static final String JWT_SUBJECT = "Login-Check";
    private static final String JWT_CUSTOMER_CLAIM_KEY = "customerClaim";
    public static final int JWT_EXPIRE_SECONDS = 1800;
    private static final int JWT_NOT_BEFORE_SECONDS = 180;

    /**
     * 根据自定义消息生成续租加密结果
     *
     * @param params
     * @return
     */
    public String generateRenewToken(String params) {
        try {
            logger.info("generate token for {}", params);
            Algorithm algorithm = getAlgorithm();
            return JWT.create()
                    //颁发者
                    .withIssuer(JWT_ISSUER)
                    //接收者
                    .withAudience(JWT_AUDIENCE)
                    .withSubject(JWT_SUBJECT)
                    .withExpiresAt(DateUtils.addSecondToDate(new Date(), JWT_EXPIRE_SECONDS))
                    .withNotBefore(DateUtils.addSecondToDate(new Date(), -JWT_NOT_BEFORE_SECONDS))
                    .withClaim(JWT_CUSTOMER_CLAIM_KEY, params)
                    .sign(algorithm);
        } catch (Exception e) {
            logger.info("generate token fail", e);
        }
        return "";
    }

    /**
     * 从token中获取之前设置的信息
     *
     * @param token
     * @return
     */
    public String getClaimFromToken(String token) {
        try {
            logger.info("verify token for {}", token);
            if (token == null || token.trim().length() == 0) {
                return "";
            }
            Algorithm algorithm = getAlgorithm();
            JWTVerifier verifier = JWT.require(algorithm)
                    .withIssuer(JWT_ISSUER)
                    .withAudience(JWT_AUDIENCE)
                    .withSubject(JWT_SUBJECT)
                    .build();
            DecodedJWT jwt = verifier.verify(token);
            String customerClaim = jwt.getClaims().get(JWT_CUSTOMER_CLAIM_KEY).asString();
            logger.info("verify success {}", customerClaim);
            return customerClaim;
        } catch (Exception e) {
            logger.info("verify fail", e);
        }
        return "";
    }

    /**
     * 初始化公、私钥，获取用于加密的RSA算法
     *
     * @return
     */
    private Algorithm getAlgorithm() throws Exception {
        if (this.publicKey == null || "".equals(this.publicKey) || this.privateKey == null || "".equals(this.privateKey)) {
            throw new RuntimeException("publicKey and privateKey can't be null");
        }
        RSAPublicKey publicKey = getRSAPublicKeyFromX509(this.publicKey);
        RSAPrivateKey privateKey = getRSAPrivateKeyFromPKCS8(this.privateKey);
        return Algorithm.RSA256(publicKey, privateKey);
    }

    /**
     * 将RSA公钥字符串转换成对象
     *
     * @param RSAPublicKey
     * @return
     * @throws Exception
     */
    private RSAPublicKey getRSAPublicKeyFromX509(String RSAPublicKey) throws Exception {
        KeyFactory keyFactory = KeyFactory.getInstance("RSA");
        byte[] encodedKey = Base64.decode(RSAPublicKey.getBytes(Charset.forName("UTF-8")));
        return (java.security.interfaces.RSAPublicKey) keyFactory.generatePublic(new X509EncodedKeySpec(encodedKey));
    }

    /**
     * 将RSA私钥字符串转换成对象
     *
     * @param RSAPrivateKey
     * @return
     * @throws Exception
     */
    private RSAPrivateKey getRSAPrivateKeyFromPKCS8(String RSAPrivateKey) throws Exception {
        KeyFactory keyFactory = KeyFactory.getInstance("RSA");
        byte[] encodedKey = Base64.decode(RSAPrivateKey.getBytes(Charset.forName("UTF-8")));
        return (java.security.interfaces.RSAPrivateKey) keyFactory.generatePrivate(new PKCS8EncodedKeySpec(encodedKey));
    }

    public String getPublicKey() {
        return publicKey;
    }

    public void setPublicKey(String publicKey) {
        this.publicKey = publicKey;
    }

    public String getPrivateKey() {
        return privateKey;
    }

    public void setPrivateKey(String privateKey) {
        this.privateKey = privateKey;
    }

    public static void main(String[] args) {
        JWTUtils utils = new JWTUtils();
        utils.setPublicKey("MIGfMA0GCSqGSIb3DQEBAQUAA4GNADCBiQKBgQC/WZcoDc/JnE6jEeuw96gNr22siUqUW1yvBpULy0mIiCFnzj2ku62QylTnP1OXnJl+7RrXJGGwAQRwL1e6zn7dmvBqhTzoJr9SEuhuTiewUXF9fwZ6WbISsItUJYse0uR+rj34NnwhWfrKSUHhKnvKiDWPbu3NB3+JLmKJAXL/vQIDAQAB");
        utils.setPrivateKey("MIICdwIBADANBgkqhkiG9w0BAQEFAASCAmEwggJdAgEAAoGBAL9ZlygNz8mcTqMR67D3qA2vbayJSpRbXK8GlQvLSYiIIWfOPaS7rZDKVOc/U5ecmX7tGtckYbABBHAvV7rOft2a8GqFPOgmv1IS6G5OJ7BRcX1/BnpZshKwi1Qlix7S5H6uPfg2fCFZ+spJQeEqe8qINY9u7c0Hf4kuYokBcv+9AgMBAAECgYEAr7WBDBLCv4t82llWaIbCFu8Ecu8PQPQ0Q7RzoQTnXSxEIKJOELsWQmLJXB/Wjt4KRXdMskqCObB1dt7CXJPKAfJL+fTmo16YmKGwou2B3q6ebFpUB/MAgqmQs4S3qZJsVMN/OENYix406HMxGNScgETYxAIvEGBDqWvqKIQuqrECQQD9jK4XVZUomndI48Nis1XXI5zoC++SzUUOT/Y4fyPROvpJ0zC3tNlBoCQfoZX8h6e3Yxnie+5NFowQz8M9IeOTAkEAwTME7dvJVMVH/FP5jou7aeV9qGJPiFwB8qrdmup3jU0gNHvy9Y+hS9w6ji6PqPzpjWs4xfYn1IMMq2rVxMNBbwJBAK9oUswr1fv4GMvhXjt7K8ihh5x1HXGm9r43DXT6aDIIpjzKkSqWP7MJ8dO8OwIwaxQQyEiKSkskbRP4V+6D8mcCQE7iTQXtssPpFV5iz0ezqB8x89+33G952dXCjF8/kvbf4eFsJqS7M4ms7z+0pTXDpnz2paS2wEaWB6tKIOSJMQMCQCPLbd+c6Dpc0VYXbRVTAwWb7J3/1oqdHfu92ZJs3rt0KL2O9JqHLvr+GTKCJ/DibrUyH9rXOEp2Udf4cw9+Lzk=");
        System.out.println(utils.generateRenewToken("{'userCode': '222746237705650176'}"));

    }
}
